#!/usr/bin/env python3
"""
用户权限管理和系统配置模块
User Management and System Configuration Module
"""

import json
import hashlib
import sqlite3
import os
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional, Any
import secrets
import configparser
from enum import Enum

class UserRole(Enum):
    """用户角色枚举"""
    ADMIN = "admin"
    OPERATOR = "operator"
    VIEWER = "viewer"
    TECHNICIAN = "technician"

class Permission(Enum):
    """权限枚举"""
    # 系统管理权限
    SYSTEM_ADMIN = "system_admin"
    USER_MANAGEMENT = "user_management"
    SYSTEM_CONFIG = "system_config"
    
    # 数据权限
    VIEW_DATA = "view_data"
    EXPORT_DATA = "export_data"
    DELETE_DATA = "delete_data"
    
    # 设备控制权限
    DEVICE_CONTROL = "device_control"
    IRRIGATION_CONTROL = "irrigation_control"
    DEVICE_MAINTENANCE = "device_maintenance"
    
    # 分析权限
    ADVANCED_ANALYTICS = "advanced_analytics"
    REPORT_GENERATION = "report_generation"
    
    # 作物管理权限
    CROP_MANAGEMENT = "crop_management"
    SCHEDULE_MANAGEMENT = "schedule_management"

@dataclass
class User:
    """用户信息"""
    user_id: str
    username: str
    email: str
    password_hash: str
    salt: str
    role: UserRole
    permissions: List[Permission]
    created_at: datetime
    last_login: Optional[datetime]
    is_active: bool
    profile: Dict[str, Any]

@dataclass
class Session:
    """用户会话"""
    session_id: str
    user_id: str
    created_at: datetime
    expires_at: datetime
    ip_address: str
    user_agent: str

@dataclass
class SystemConfig:
    """系统配置"""
    config_id: str
    section: str
    key: str
    value: str
    description: str
    data_type: str  # string, int, float, bool, json
    is_sensitive: bool
    modified_at: datetime
    modified_by: str

class UserManager:
    """用户管理器"""
    
    def __init__(self, db_path: str = "enhanced_agriculture.db"):
        self.db_path = db_path
        self.init_user_tables()
        self.role_permissions = self._setup_role_permissions()
        self.active_sessions = {}
    
    def init_user_tables(self):
        """初始化用户相关表"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # 用户表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                user_id TEXT PRIMARY KEY,
                username TEXT UNIQUE NOT NULL,
                email TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                salt TEXT NOT NULL,
                role TEXT NOT NULL,
                permissions TEXT,
                created_at TEXT NOT NULL,
                last_login TEXT,
                is_active INTEGER DEFAULT 1,
                profile TEXT
            )
        ''')
        
        # 会话表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_sessions (
                session_id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                created_at TEXT NOT NULL,
                expires_at TEXT NOT NULL,
                ip_address TEXT,
                user_agent TEXT,
                FOREIGN KEY (user_id) REFERENCES users (user_id)
            )
        ''')
        
        # 操作日志表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id TEXT NOT NULL,
                action TEXT NOT NULL,
                target TEXT,
                details TEXT,
                ip_address TEXT,
                timestamp TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users (user_id)
            )
        ''')
        
        conn.commit()
        
        # 创建默认管理员账户
        self._create_default_admin()
        
        conn.close()
    
    def _setup_role_permissions(self) -> Dict[UserRole, List[Permission]]:
        """设置角色权限映射"""
        return {
            UserRole.ADMIN: [
                Permission.SYSTEM_ADMIN,
                Permission.USER_MANAGEMENT,
                Permission.SYSTEM_CONFIG,
                Permission.VIEW_DATA,
                Permission.EXPORT_DATA,
                Permission.DELETE_DATA,
                Permission.DEVICE_CONTROL,
                Permission.IRRIGATION_CONTROL,
                Permission.DEVICE_MAINTENANCE,
                Permission.ADVANCED_ANALYTICS,
                Permission.REPORT_GENERATION,
                Permission.CROP_MANAGEMENT,
                Permission.SCHEDULE_MANAGEMENT
            ],
            UserRole.OPERATOR: [
                Permission.VIEW_DATA,
                Permission.EXPORT_DATA,
                Permission.DEVICE_CONTROL,
                Permission.IRRIGATION_CONTROL,
                Permission.CROP_MANAGEMENT,
                Permission.SCHEDULE_MANAGEMENT,
                Permission.REPORT_GENERATION
            ],
            UserRole.TECHNICIAN: [
                Permission.VIEW_DATA,
                Permission.DEVICE_CONTROL,
                Permission.DEVICE_MAINTENANCE,
                Permission.IRRIGATION_CONTROL,
                Permission.EXPORT_DATA
            ],
            UserRole.VIEWER: [
                Permission.VIEW_DATA,
                Permission.EXPORT_DATA
            ]
        }
    
    def _create_default_admin(self):
        """创建默认管理员账户"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        # 检查是否已存在管理员
        cursor.execute("SELECT COUNT(*) FROM users WHERE role = ?", (UserRole.ADMIN.value,))
        admin_count = cursor.fetchone()[0]
        
        if admin_count == 0:
            # 创建默认管理员
            admin_user = self.create_user(
                username="admin",
                email="admin@agriculture.local",
                password="admin123",
                role=UserRole.ADMIN,
                profile={
                    "full_name": "系统管理员",
                    "department": "系统管理",
                    "phone": "",
                    "notes": "默认管理员账户"
                }
            )
            print("✅ 已创建默认管理员账户: admin/admin123")
        
        conn.close()
    
    def hash_password(self, password: str, salt: str = None) -> tuple:
        """哈希密码"""
        if salt is None:
            salt = secrets.token_hex(32)
        
        password_hash = hashlib.pbkdf2_hmac(
            'sha256',
            password.encode('utf-8'),
            salt.encode('utf-8'),
            100000  # 迭代次数
        ).hex()
        
        return password_hash, salt
    
    def verify_password(self, password: str, password_hash: str, salt: str) -> bool:
        """验证密码"""
        hash_to_check, _ = self.hash_password(password, salt)
        return hash_to_check == password_hash
    
    def create_user(self, username: str, email: str, password: str, 
                   role: UserRole, profile: Dict = None) -> Optional[User]:
        """创建用户"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 检查用户名和邮箱是否已存在
            cursor.execute("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?", 
                          (username, email))
            if cursor.fetchone()[0] > 0:
                raise ValueError("用户名或邮箱已存在")
            
            # 生成用户ID和密码哈希
            user_id = secrets.token_hex(16)
            password_hash, salt = self.hash_password(password)
            
            # 获取角色权限
            permissions = self.role_permissions.get(role, [])
            permissions_json = json.dumps([p.value for p in permissions])
            
            # 创建用户对象
            user = User(
                user_id=user_id,
                username=username,
                email=email,
                password_hash=password_hash,
                salt=salt,
                role=role,
                permissions=permissions,
                created_at=datetime.now(),
                last_login=None,
                is_active=True,
                profile=profile or {}
            )
            
            # 保存到数据库
            cursor.execute('''
                INSERT INTO users (user_id, username, email, password_hash, salt, 
                                 role, permissions, created_at, last_login, is_active, profile)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                user.user_id,
                user.username,
                user.email,
                user.password_hash,
                user.salt,
                user.role.value,
                permissions_json,
                user.created_at.isoformat(),
                None,
                1 if user.is_active else 0,
                json.dumps(user.profile, ensure_ascii=False)
            ))
            
            conn.commit()
            conn.close()
            
            # 记录操作日志
            self.log_user_action("system", "user_created", username, 
                                {"role": role.value, "email": email})
            
            return user
            
        except Exception as e:
            print(f"创建用户失败: {e}")
            return None
    
    def authenticate_user(self, username: str, password: str, 
                         ip_address: str = "", user_agent: str = "") -> Optional[Session]:
        """用户认证"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 查找用户
            cursor.execute('''
                SELECT user_id, password_hash, salt, is_active 
                FROM users WHERE username = ?
            ''', (username,))
            
            result = cursor.fetchone()
            if not result:
                self.log_user_action("unknown", "login_failed", username, 
                                    {"reason": "user_not_found", "ip": ip_address})
                return None
            
            user_id, password_hash, salt, is_active = result
            
            # 检查账户是否激活
            if not is_active:
                self.log_user_action(user_id, "login_failed", username, 
                                    {"reason": "account_disabled", "ip": ip_address})
                return None
            
            # 验证密码
            if not self.verify_password(password, password_hash, salt):
                self.log_user_action(user_id, "login_failed", username, 
                                    {"reason": "invalid_password", "ip": ip_address})
                return None
            
            # 创建会话
            session = self.create_session(user_id, ip_address, user_agent)
            
            # 更新最后登录时间
            cursor.execute("UPDATE users SET last_login = ? WHERE user_id = ?",
                          (datetime.now().isoformat(), user_id))
            
            conn.commit()
            conn.close()
            
            # 记录登录成功
            self.log_user_action(user_id, "login_success", username, 
                                {"ip": ip_address, "session_id": session.session_id})
            
            return session
            
        except Exception as e:
            print(f"用户认证失败: {e}")
            return None
    
    def create_session(self, user_id: str, ip_address: str, user_agent: str) -> Session:
        """创建用户会话"""
        session = Session(
            session_id=secrets.token_urlsafe(32),
            user_id=user_id,
            created_at=datetime.now(),
            expires_at=datetime.now() + timedelta(hours=8),  # 8小时过期
            ip_address=ip_address,
            user_agent=user_agent
        )
        
        # 保存会话到数据库
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            INSERT INTO user_sessions (session_id, user_id, created_at, expires_at, 
                                     ip_address, user_agent)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            session.session_id,
            session.user_id,
            session.created_at.isoformat(),
            session.expires_at.isoformat(),
            session.ip_address,
            session.user_agent
        ))
        
        conn.commit()
        conn.close()
        
        # 缓存活动会话
        self.active_sessions[session.session_id] = session
        
        return session
    
    def validate_session(self, session_id: str) -> Optional[User]:
        """验证会话"""
        # 检查缓存
        if session_id in self.active_sessions:
            session = self.active_sessions[session_id]
            if session.expires_at > datetime.now():
                return self.get_user_by_id(session.user_id)
            else:
                # 会话已过期
                del self.active_sessions[session_id]
                self.cleanup_expired_session(session_id)
        
        # 从数据库检查
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT user_id, expires_at FROM user_sessions 
            WHERE session_id = ?
        ''', (session_id,))
        
        result = cursor.fetchone()
        conn.close()
        
        if result:
            user_id, expires_at_str = result
            expires_at = datetime.fromisoformat(expires_at_str)
            
            if expires_at > datetime.now():
                return self.get_user_by_id(user_id)
            else:
                # 会话已过期
                self.cleanup_expired_session(session_id)
        
        return None
    
    def logout_user(self, session_id: str):
        """用户登出"""
        if session_id in self.active_sessions:
            session = self.active_sessions[session_id]
            self.log_user_action(session.user_id, "logout", "", {"session_id": session_id})
            del self.active_sessions[session_id]
        
        # 从数据库删除会话
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("DELETE FROM user_sessions WHERE session_id = ?", (session_id,))
        conn.commit()
        conn.close()
    
    def cleanup_expired_session(self, session_id: str):
        """清理过期会话"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        cursor.execute("DELETE FROM user_sessions WHERE session_id = ?", (session_id,))
        conn.commit()
        conn.close()
    
    def get_user_by_id(self, user_id: str) -> Optional[User]:
        """根据ID获取用户"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
        result = cursor.fetchone()
        conn.close()
        
        if result:
            return self._row_to_user(result)
        return None
    
    def get_user_by_username(self, username: str) -> Optional[User]:
        """根据用户名获取用户"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
        result = cursor.fetchone()
        conn.close()
        
        if result:
            return self._row_to_user(result)
        return None
    
    def _row_to_user(self, row) -> User:
        """数据库行转换为用户对象"""
        permissions_json = row[6] if row[6] else "[]"
        permissions = [Permission(p) for p in json.loads(permissions_json)]
        
        profile_json = row[10] if row[10] else "{}"
        profile = json.loads(profile_json)
        
        last_login = None
        if row[8]:
            last_login = datetime.fromisoformat(row[8])
        
        return User(
            user_id=row[0],
            username=row[1],
            email=row[2],
            password_hash=row[3],
            salt=row[4],
            role=UserRole(row[5]),
            permissions=permissions,
            created_at=datetime.fromisoformat(row[7]),
            last_login=last_login,
            is_active=bool(row[9]),
            profile=profile
        )
    
    def update_user(self, user_id: str, updates: Dict[str, Any], 
                   updated_by: str) -> bool:
        """更新用户信息"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            # 构建更新SQL
            set_clauses = []
            values = []
            
            for key, value in updates.items():
                if key in ['email', 'role', 'is_active', 'profile']:
                    set_clauses.append(f"{key} = ?")
                    if key == 'role' and isinstance(value, UserRole):
                        values.append(value.value)
                    elif key == 'profile':
                        values.append(json.dumps(value, ensure_ascii=False))
                    else:
                        values.append(value)
            
            if set_clauses:
                sql = f"UPDATE users SET {', '.join(set_clauses)} WHERE user_id = ?"
                values.append(user_id)
                
                cursor.execute(sql, values)
                conn.commit()
                
                # 记录操作日志
                self.log_user_action(updated_by, "user_updated", user_id, updates)
                
            conn.close()
            return True
            
        except Exception as e:
            print(f"更新用户失败: {e}")
            return False
    
    def change_password(self, user_id: str, old_password: str, 
                       new_password: str) -> bool:
        """修改密码"""
        try:
            user = self.get_user_by_id(user_id)
            if not user:
                return False
            
            # 验证旧密码
            if not self.verify_password(old_password, user.password_hash, user.salt):
                return False
            
            # 生成新密码哈希
            new_hash, new_salt = self.hash_password(new_password)
            
            # 更新数据库
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                UPDATE users SET password_hash = ?, salt = ? WHERE user_id = ?
            ''', (new_hash, new_salt, user_id))
            
            conn.commit()
            conn.close()
            
            # 记录操作日志
            self.log_user_action(user_id, "password_changed", "", {})
            
            return True
            
        except Exception as e:
            print(f"修改密码失败: {e}")
            return False
    
    def log_user_action(self, user_id: str, action: str, target: str, 
                       details: Dict, ip_address: str = ""):
        """记录用户操作日志"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                INSERT INTO user_logs (user_id, action, target, details, ip_address, timestamp)
                VALUES (?, ?, ?, ?, ?, ?)
            ''', (
                user_id,
                action,
                target,
                json.dumps(details, ensure_ascii=False),
                ip_address,
                datetime.now().isoformat()
            ))
            
            conn.commit()
            conn.close()
            
        except Exception as e:
            print(f"记录日志失败: {e}")
    
    def get_user_logs(self, user_id: str = None, limit: int = 100) -> List[Dict]:
        """获取用户操作日志"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        if user_id:
            cursor.execute('''
                SELECT * FROM user_logs WHERE user_id = ? 
                ORDER BY timestamp DESC LIMIT ?
            ''', (user_id, limit))
        else:
            cursor.execute('''
                SELECT * FROM user_logs ORDER BY timestamp DESC LIMIT ?
            ''', (limit,))
        
        results = cursor.fetchall()
        conn.close()
        
        logs = []
        for row in results:
            logs.append({
                'id': row[0],
                'user_id': row[1],
                'action': row[2],
                'target': row[3],
                'details': json.loads(row[4]) if row[4] else {},
                'ip_address': row[5],
                'timestamp': datetime.fromisoformat(row[6])
            })
        
        return logs
    
    def has_permission(self, user: User, permission: Permission) -> bool:
        """检查用户权限"""
        return permission in user.permissions
    
    def list_users(self, active_only: bool = True) -> List[User]:
        """列出所有用户"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        if active_only:
            cursor.execute("SELECT * FROM users WHERE is_active = 1 ORDER BY username")
        else:
            cursor.execute("SELECT * FROM users ORDER BY username")
        
        results = cursor.fetchall()
        conn.close()
        
        return [self._row_to_user(row) for row in results]

class SystemConfigManager:
    """系统配置管理器"""
    
    def __init__(self, db_path: str = "enhanced_agriculture.db"):
        self.db_path = db_path
        self.init_config_tables()
        self.load_default_configs()
    
    def init_config_tables(self):
        """初始化配置表"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS system_config (
                config_id TEXT PRIMARY KEY,
                section TEXT NOT NULL,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                description TEXT,
                data_type TEXT DEFAULT 'string',
                is_sensitive INTEGER DEFAULT 0,
                modified_at TEXT NOT NULL,
                modified_by TEXT NOT NULL,
                UNIQUE(section, key)
            )
        ''')
        
        conn.commit()
        conn.close()
    
    def load_default_configs(self):
        """加载默认配置"""
        default_configs = [
            # 系统配置
            ("system", "app_name", "智慧农业边缘控制系统", "应用程序名称", "string", False),
            ("system", "version", "2.0.0", "系统版本", "string", False),
            ("system", "debug_mode", "false", "调试模式", "bool", False),
            ("system", "log_level", "INFO", "日志级别", "string", False),
            
            # 数据库配置
            ("database", "auto_backup", "true", "自动备份", "bool", False),
            ("database", "backup_interval_hours", "24", "备份间隔(小时)", "int", False),
            ("database", "max_backup_files", "7", "最大备份文件数", "int", False),
            ("database", "cleanup_days", "90", "数据清理天数", "int", False),
            
            # 传感器配置
            ("sensors", "data_interval_seconds", "5", "数据采集间隔(秒)", "int", False),
            ("sensors", "calibration_interval_days", "30", "校准间隔(天)", "int", False),
            ("sensors", "alert_thresholds", '{"soil_moisture_low": 25, "temperature_high": 35}', "告警阈值", "json", False),
            
            # 灌溉配置
            ("irrigation", "auto_mode", "true", "自动灌溉模式", "bool", False),
            ("irrigation", "max_duration_minutes", "60", "最大灌溉时长(分钟)", "int", False),
            ("irrigation", "flow_rate_lpm", "15", "默认流量(L/min)", "float", False),
            
            # 设备配置
            ("devices", "health_check_interval_minutes", "10", "健康检查间隔(分钟)", "int", False),
            ("devices", "maintenance_reminder_days", "7", "维护提醒提前天数", "int", False),
            
            # 安全配置
            ("security", "session_timeout_hours", "8", "会话超时时间(小时)", "int", False),
            ("security", "max_login_attempts", "5", "最大登录尝试次数", "int", False),
            ("security", "password_min_length", "6", "密码最小长度", "int", False),
            
            # 通知配置
            ("notifications", "email_enabled", "false", "邮件通知", "bool", False),
            ("notifications", "sms_enabled", "false", "短信通知", "bool", False),
            ("notifications", "alert_levels", '["high", "critical"]', "告警级别", "json", False),
            
            # API配置
            ("api", "rate_limit_per_minute", "100", "API速率限制(次/分钟)", "int", False),
            ("api", "enable_cors", "true", "启用CORS", "bool", False),
            
            # 界面配置
            ("ui", "theme", "light", "界面主题", "string", False),
            ("ui", "language", "zh-CN", "界面语言", "string", False),
            ("ui", "chart_refresh_seconds", "30", "图表刷新间隔(秒)", "int", False),
        ]
        
        for section, key, value, description, data_type, is_sensitive in default_configs:
            self.set_config(section, key, value, description, data_type, is_sensitive, "system")
    
    def set_config(self, section: str, key: str, value: str, 
                  description: str = "", data_type: str = "string", 
                  is_sensitive: bool = False, modified_by: str = "system") -> bool:
        """设置配置项"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            config_id = f"{section}.{key}"
            
            cursor.execute('''
                INSERT OR REPLACE INTO system_config 
                (config_id, section, key, value, description, data_type, 
                 is_sensitive, modified_at, modified_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
                config_id, section, key, value, description, data_type,
                1 if is_sensitive else 0, datetime.now().isoformat(), modified_by
            ))
            
            conn.commit()
            conn.close()
            return True
            
        except Exception as e:
            print(f"设置配置失败: {e}")
            return False
    
    def get_config(self, section: str, key: str, default_value: Any = None) -> Any:
        """获取配置项"""
        try:
            conn = sqlite3.connect(self.db_path)
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT value, data_type FROM system_config 
                WHERE section = ? AND key = ?
            ''', (section, key))
            
            result = cursor.fetchone()
            conn.close()
            
            if result:
                value, data_type = result
                return self._convert_config_value(value, data_type)
            
            return default_value
            
        except Exception as e:
            print(f"获取配置失败: {e}")
            return default_value
    
    def _convert_config_value(self, value: str, data_type: str) -> Any:
        """转换配置值类型"""
        try:
            if data_type == "int":
                return int(value)
            elif data_type == "float":
                return float(value)
            elif data_type == "bool":
                return value.lower() in ("true", "1", "yes", "on")
            elif data_type == "json":
                return json.loads(value)
            else:
                return value
        except:
            return value
    
    def get_section_configs(self, section: str) -> Dict[str, Any]:
        """获取某个section的所有配置"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            SELECT key, value, data_type FROM system_config 
            WHERE section = ? ORDER BY key
        ''', (section,))
        
        results = cursor.fetchall()
        conn.close()
        
        configs = {}
        for key, value, data_type in results:
            configs[key] = self._convert_config_value(value, data_type)
        
        return configs
    
    def list_all_configs(self, include_sensitive: bool = False) -> List[SystemConfig]:
        """列出所有配置"""
        conn = sqlite3.connect(self.db_path)
        cursor = conn.cursor()
        
        if include_sensitive:
            cursor.execute("SELECT * FROM system_config ORDER BY section, key")
        else:
            cursor.execute("SELECT * FROM system_config WHERE is_sensitive = 0 ORDER BY section, key")
        
        results = cursor.fetchall()
        conn.close()
        
        configs = []
        for row in results:
            config = SystemConfig(
                config_id=row[0],
                section=row[1],
                key=row[2],
                value=row[3],
                description=row[4],
                data_type=row[5],
                is_sensitive=bool(row[6]),
                modified_at=datetime.fromisoformat(row[7]),
                modified_by=row[8]
            )
            configs.append(config)
        
        return configs
    
    def export_config(self, file_path: str, include_sensitive: bool = False) -> bool:
        """导出配置到文件"""
        try:
            configs = self.list_all_configs(include_sensitive)
            
            config_dict = {}
            for config in configs:
                if config.section not in config_dict:
                    config_dict[config.section] = {}
                
                config_dict[config.section][config.key] = {
                    'value': config.value,
                    'description': config.description,
                    'data_type': config.data_type,
                    'is_sensitive': config.is_sensitive
                }
            
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(config_dict, f, ensure_ascii=False, indent=2)
            
            return True
            
        except Exception as e:
            print(f"导出配置失败: {e}")
            return False
    
    def import_config(self, file_path: str, modified_by: str) -> bool:
        """从文件导入配置"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                config_dict = json.load(f)
            
            for section, configs in config_dict.items():
                for key, config_data in configs.items():
                    self.set_config(
                        section=section,
                        key=key,
                        value=config_data['value'],
                        description=config_data.get('description', ''),
                        data_type=config_data.get('data_type', 'string'),
                        is_sensitive=config_data.get('is_sensitive', False),
                        modified_by=modified_by
                    )
            
            return True
            
        except Exception as e:
            print(f"导入配置失败: {e}")
            return False

def create_login_dialog():
    """创建登录对话框"""
    import tkinter as tk
    from tkinter import ttk, messagebox
    
    class LoginDialog:
        def __init__(self):
            self.root = tk.Tk()
            self.root.title("用户登录")
            self.root.geometry("400x300")
            self.root.resizable(False, False)
            
            self.user_manager = UserManager()
            self.current_user = None
            
            self.setup_ui()
            
        def setup_ui(self):
            # 标题
            title_label = tk.Label(self.root, text="智慧农业系统", font=('微软雅黑', 20, 'bold'), fg='#2e8b57')
            title_label.pack(pady=30)
            
            # 登录表单
            form_frame = tk.Frame(self.root)
            form_frame.pack(pady=20)
            
            # 用户名
            tk.Label(form_frame, text="用户名:", font=('微软雅黑', 12)).grid(row=0, column=0, sticky='e', padx=10, pady=10)
            self.username_entry = tk.Entry(form_frame, font=('微软雅黑', 12), width=20)
            self.username_entry.grid(row=0, column=1, padx=10, pady=10)
            
            # 密码
            tk.Label(form_frame, text="密码:", font=('微软雅黑', 12)).grid(row=1, column=0, sticky='e', padx=10, pady=10)
            self.password_entry = tk.Entry(form_frame, font=('微软雅黑', 12), width=20, show='*')
            self.password_entry.grid(row=1, column=1, padx=10, pady=10)
            
            # 按钮
            button_frame = tk.Frame(self.root)
            button_frame.pack(pady=20)
            
            login_btn = tk.Button(button_frame, text="登录", font=('微软雅黑', 12), 
                                 bg='#2e8b57', fg='white', width=8, command=self.login)
            login_btn.pack(side='left', padx=10)
            
            cancel_btn = tk.Button(button_frame, text="取消", font=('微软雅黑', 12), 
                                  width=8, command=self.root.quit)
            cancel_btn.pack(side='left', padx=10)
            
            # 绑定回车键
            self.root.bind('<Return>', lambda e: self.login())
            
            # 默认焦点
            self.username_entry.focus()
            
            # 提示信息
            tip_label = tk.Label(self.root, text="默认账户: admin / admin123", 
                                font=('微软雅黑', 10), fg='gray')
            tip_label.pack(pady=10)
        
        def login(self):
            username = self.username_entry.get().strip()
            password = self.password_entry.get()
            
            if not username or not password:
                messagebox.showwarning("输入错误", "请输入用户名和密码")
                return
            
            session = self.user_manager.authenticate_user(username, password, "127.0.0.1", "Desktop App")
            
            if session:
                self.current_user = self.user_manager.get_user_by_id(session.user_id)
                messagebox.showinfo("登录成功", f"欢迎, {self.current_user.username}!")
                self.root.destroy()
            else:
                messagebox.showerror("登录失败", "用户名或密码错误")
                self.password_entry.delete(0, tk.END)
        
        def get_current_user(self):
            return self.current_user
    
    return LoginDialog()

if __name__ == "__main__":
    # 测试用户管理功能
    dialog = create_login_dialog()
    dialog.root.mainloop()
    
    user = dialog.get_current_user()
    if user:
        print(f"当前用户: {user.username}, 角色: {user.role.value}")
        print(f"权限: {[p.value for p in user.permissions]}")